package com.qikux.controller;

import cn.hutool.core.io.FileUtil;
import com.qikux.annotation.*;
import com.qikux.annotition.Authentication;
import com.qikux.consts.AppConst;
import com.qikux.dao.DetailDao;
import com.qikux.entity.Notice;
import com.qikux.entity.User;
import com.qikux.entity.UserInfo;
import com.qikux.service.DetailService;
import com.qikux.utils.ContextUtils;
import com.qikux.utils.RSAUtils;
import com.qikux.utils.UploadUtils;
import com.qikux.vo.HttpEntity;
import com.qikux.vo.Page;
import com.qikux.vo.ResourceVo;
import com.qikux.vo.ResultVo;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RequestMapping("/resource")
@Component
public class DetailController {

    String pt = this.getClass().getResource("/").getPath().replaceFirst("/", "");
    String webappRoot = pt.replaceAll("target/downloadLover-1.0-SNAPSHOT/WEB-INF/classes/", "src/main/webapp/upload");
    // 维护一个业务逻辑层对象
    @Resource
    private DetailService detailService;
    @Resource
    private DetailDao detailDao;

    @RequestMapping(value = "/detail",method = RequestMethod.GET)
    public String detailIndex(){
        // 获取页面传来的资源id参数
        Long resId = Long.parseLong(ContextUtils.getRequest().getParameter("resId"));

        User user = (User)ContextUtils.getSession().getAttribute(AppConst.LOGIN_FLAG);

        // 调用业务逻辑层处理该业务
        ResultVo<ResourceVo> resultVo = detailService.queryResourceById(resId, user);

        int downloadCount = detailService.queryDownloadCount(resId);

        // 当返回的状态为false时
        if (!resultVo.isStatus()){
            // 设置请求，键为errorMsg,值为resultVo.getMessage()
            // 同时转发到fail页面
            ContextUtils.getRequest().setAttribute("errorMsg",resultVo.getMessage());
            return "fail";
        }

        // 另一种情况，设置请求的键为resource,值为resultVo.getData()
        // 同时转发到detail页面
        ContextUtils.getRequest().setAttribute("resource",resultVo.getData());
        ContextUtils.getRequest().setAttribute("downloadCount",downloadCount);

        return "detail";
    }

    @Authentication
    @RequestMapping(value = "/collect",method = RequestMethod.GET)
    @ResponseBody
    public ResultVo<String> collect(){
        Long resId = Long.parseLong(ContextUtils.getRequest().getParameter("resId"));
        User user = (User) ContextUtils.getSession().getAttribute(AppConst.LOGIN_FLAG);
        Long userId = user.getId();
        return detailService.collect(resId,userId);
    }

    @RequestMapping(value = "/comment",method = RequestMethod.GET)
    @ResponseBody
    public ResultVo<Page<Map<String, Object>>> comment(){
        Long resId = Long.parseLong(ContextUtils.getRequest().getParameter("resId"));

        // 分页查询, 获取页码
        String page = ContextUtils.getRequest().getParameter("page");
        if (page == null || "".equals(page)) page = "1";
        int _page = Integer.parseInt(page);

        /**
         * 包含了分页参数
         */
        Page<Map<String,Object>> pageBean = Page.builder().rows(5).page(_page).build();

        return detailService.comment(resId,pageBean);
    }

    @ResponseBody
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public ResultVo<UserInfo> userInfo(){
        Long userId = Long.parseLong(ContextUtils.getRequest().getParameter("userId"));
        UserInfo userInfo = detailService.queryUserInfoByUserId(userId);
        return ResultVo.ok().body(userInfo);
    }

    @RequestMapping(value = "/photo",method = RequestMethod.GET)
    public HttpEntity showPhoto(){
        String userId = ContextUtils.getRequest().getParameter("u");

        Map<String, Object> photoPath = detailService.getPhotoPath(Long.parseLong(userId));

        // 获取用户头像路径
        String path = String.valueOf(photoPath.get("photo"));

        File file = null;
        // 如果没有头像,则显示默认头像
        if (path == null || "null".equals(path)){
            String realpath = ContextUtils.getApplication().getRealPath("images/unknown.png") ;
            file = new File(realpath);
        }else {
            file = UploadUtils.findFile(webappRoot,path);
        }

        return new HttpEntity(FileUtil.readBytes(file), "", false);
    }

    @Authentication
    @RequestMapping(value = "/down",method = RequestMethod.GET)
    @ResponseBody
    public ResultVo<Map<String,Object>> downx() throws Exception {
        // 获取页面传来的资源id
        Long resId = Long.parseLong(ContextUtils.getRequest().getParameter("resId"));
        Long resUid = Long.parseLong(ContextUtils.getRequest().getParameter("uId"));
        // 获取用户id
        User user = (User)ContextUtils.getSession().getAttribute(AppConst.LOGIN_FLAG);
        // 调用业务逻辑层处理业务
        ResultVo<Map<String, Object>> resultVo = detailService.isSelfRes(user, resId);
        if (resultVo.isStatus() && user.getId() != resUid){
            ResourceVo resourceById = detailDao.findResourceById(resId);
            Notice notice = Notice.builder()
                    .remark(AppConst.DOWNLOAD)
                    .content(user.getInfo().getNickName() + AppConst.content_DOWNLOAD + "《"+resourceById.getResourceName()+ "》")
                    .userId(resourceById.getUserId())
                    .tagUserId(user.getId())
                    .resId(resId)
                    .build();
            Notice notice1 = detailDao.findNoticeByUserIdAndContent(notice);
            if (notice1 == null){
                detailDao.saveNotice(notice);
            }
        }
        return resultVo;
    }

    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String deduct = request.getParameter("deduct");
        String record = request.getParameter("record");
        String score = request.getParameter("score");
        String path = request.getParameter("path");
        String ext = request.getParameter("ext");
        String fileName = request.getParameter("fileName");
        String sign = request.getParameter("sign");
        StringBuilder sb = new StringBuilder();
        String s = sb.append("?record=" + record).append("&deduct=" + deduct).append("&score=" + score).toString();
        if (!RSAUtils.verify(s,sign)){
            ContextUtils.getResponse().setStatus(403);
            return;
        }
        File file = UploadUtils.findFile("upload.res.dir", path);
        byte[] bytes = FileUtil.readBytes(file);
        String encode = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachment;filename="+encode+"."+ext);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);

    }
}
